const express = require('express');
const dotenv = require('dotenv');
const employeeRouter = require('./routes/employee');
const attendanceRouter = require("./routes/attendance");
const accountRouter = require("./routes/accounts");
const leaveRouter = require("./routes/leave")
const payrollRouter = require("./routes/payroll")
const cors = require('cors');
const cookieParser = require('cookie-parser');

const { log } = require('console');
const jwt = require('jsonwebtoken');
dotenv.config();

//引入考勤机器人
require("./robot/attendance")
// //模拟触发考勤机器人（测试完成后注释掉）
// const AttendanceRobot = require("./testRobot/attendentce")
// AttendanceRobot.robot1()
// AttendanceRobot.robot2()

// //生成随机密钥（只用于一次性生成，生成后注释掉）
// const crypto = require('crypto')
// const secret = crypto.randomBytes(16).toString('hex')
// console.log(secret)   // 打印生成的密钥



const app = express();
app.use(cookieParser());

//定义token验证中间件
// const verifyToken = (req, res, next) => {
//     const token = req.cookies.token
//     if (!token) {
//         return res.status(200).json({ code: 200, message: "未登录" })
//     }
//     try {
//         const decoded = jwt.verify(token, process.env.JWT_SECRET)
//         req.user = decoded
//         next()
//     } catch (error) {
//         return res.status(401).json({ code: 401, message: error.message })
//     }
// }

app.use(express.json());
app.use(cors({
    origin: ["http://localhost:5173", "http://127.0.0.1:5173","http://8.134.187.216:5173"],  // 添加所有可能的前端地址
    credentials: true, // 允许跨域携带 cookie
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], // 允许的请求方法
    allowedHeaders: ['Content-Type', 'Authorization', 'Cookie'],  // 添加 Cookie 头
    exposedHeaders: ['set-cookie'],  // 允许前端访问 set-cookie 头
}));
//前端路由用来检测是否有token的接口
// app.get('/api/verify-token', verifyToken, (req, res) => {
//     res.status(200).json({ code: 200, authenticated: true })
// })
//清除cookie的接口
app.get('/api/quit', (req, res) => {
    try {
        res.clearCookie("token", {
            httpOnly: true,// 防止客户端脚本访问
            sameSite: "lax",// 防止跨站请求伪造（CSRF）
            secure: false, // 如果使用 HTTPS，请将 secure 设置为 true
            path: "/"
        })
        res.status(200).json({ code: 200, message: "退出成功" })
    } catch (error) {
        res.status(500).json({ code: 500, message: error.message })
    }
})
//其他接口
app.use("/api/employees", employeeRouter);
app.use("/api/accounts", accountRouter)
app.use("/api/attendance" , attendanceRouter)
app.use("/api/leave" , leaveRouter)
app.use("/api/payroll" , payrollRouter)
app.get('/', (req, res) => {
    res.send('欢迎使用人力资源管理系统API');
});

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
    console.log(`服务器运行在端口 ${PORT}`);
});
